package com.bn.userprofile;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.transaction.TransactionManager;

import com.bn.commerce.order.BNCreditCardTools;
import com.bn.util.ProfileConstants;
import com.bn.util.ValidationManager;


import atg.beans.PropertyNotFoundException;
import atg.commerce.profile.CommercePropertyManager;
import atg.commerce.util.RepeatingRequestMonitor;
import atg.core.util.ContactInfo;
import atg.core.util.ResourceUtils;
import atg.core.util.StringUtils;
import atg.droplet.DropletException;
import atg.droplet.DropletFormException;
import atg.dtm.TransactionDemarcation;
import atg.dtm.TransactionDemarcationException;
import atg.projects.store.profile.StoreProfileFormHandler;
import atg.projects.store.profile.StoreProfileTools;
import atg.projects.store.profile.StorePropertyManager;
import atg.repository.MutableRepositoryItem;
import atg.repository.RepositoryException;
import atg.repository.RepositoryItem;
import atg.security.IdentityManager;
import atg.security.SecurityException;
import atg.servlet.DynamoHttpServletRequest;
import atg.servlet.DynamoHttpServletResponse;
import atg.userprofiling.Profile;
import atg.userprofiling.ProfileTools;
import atg.userprofiling.PropertyManager;

/**
 *
 * @author atg
 *
 */
public class BNProfileFormHandler extends StoreProfileFormHandler
{
	private static final String CONFIRMEMAIL_PARAM = "confirmEmail";
	private static final String MISSINGFIRSTNAME = "missingFirstNameField";
	private static final String MISSINGLASTNAME = "missingLastNameField";
	private static final String MISSINGEMAILNAME = "missingEmailField";
	private static final String INVALIDEMAILFIELD = "invalidEmailField";
	private static final String MISSINGCONFIRMFIELD = "missingConfirmEmailField";
	private static final String MISSINGPASSWORD = "missingPassowrdField";
	private static final String PWDDOESNOTMATCH = "pwdDoesntMatch";
	private static final String SECURITY_ANSWER = "securityAnswer";
	private static final String SECURITY_ANSWER_IS_EMPTY = "securityAnswerIsEmpty";
	private static final String SECURITY_QUESTION_UPDATE= "isSecurityQuestionUpdate";
	private static final String FIRST_NAME_UPDATED= "isFirstNameUpdated";
	private static final String LAST_NAME_UPDATED= "isLastNameUpdated";
	private static final String PASSWORD_UPDATED= "isPasswordUpdated";
	private static final String WRONGPOSTALCODE = "wrongPostalCode";
	private static final String WRONGPHONENO = "wrongPhoneNo";
	private static final String APPEND_MISSING_ERROR_KEY = "Missing";
	private static final String PHONE_TYPE_UPDATE= "isphoneTypeUpdate";
	private static final String PHONE_TYPE_EMPTY = "phoneTypeEmpty";
	private static final String NAME_ON_CARD = "nameOnCard";
	private static final String MEMBERSHIP_ID = "A123";

	private  IdentityManager identityManager;
	private  ContactInfo profileContact;
	private String addressSuccessURL;
	private String addressErrorURL;
	private ValidationManager validationManager;
	private boolean useShippingAddressAsDefault;
	private String createCardSuccessURL;
	private String createCardErrorURL;
	private String loginSuccessURL;
	private String loginErrorURL;
	private String updatePhoneTypeSuccessURL;
	private String updatePhoneTypeErrorURL;
	private String updateSecurityQuesSuccessURL;
	private String updateSecurityQuesErrorURL;
	private String deleteAddressFromAddressBookSuccessURL;
	private String deleteAddressFromAddressBookErrorURL;
	private RepeatingRequestMonitor mRepeatingRequestMonitor;
	private BNProfileManager profileManager;
	private String nickName;
	private String UpdateDefaultShipAddressSuccessURL;
	private String UpdateDefaultShipAddressErrorURL;
	private String creditCardID;
	private String UpdateCreditCardErrorURL;
	private String UpdateCreditCardSuccessURL;
	private String membershipId;

	public  BNProfileFormHandler() {
		profileContact = new ContactInfo();
	}


	protected void preCreateUser(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {

		StorePropertyManager storePropertyManager =  (StorePropertyManager) getProfileTools().getPropertyManager();

		if (!getStringValueProperty(storePropertyManager.getEmailAddressPropertyName()).equalsIgnoreCase(getStringValueProperty(CONFIRMEMAIL_PARAM))){
			String msg = formatUserMessage("confirmEmailDoNotMatch", pRequest);
			String path = generatePropertyPath(CONFIRMEMAIL_PARAM);
			addFormException(new DropletFormException(msg, path));
		}
		validateEmptyFields (pRequest);
		String loginProperty = storePropertyManager.getLoginPropertyName();

		String email = (String) getValue().get(storePropertyManager.getEmailAddressPropertyName());

		setValueProperty(loginProperty,email);
		getValue().remove(CONFIRMEMAIL_PARAM);
	}


	private void validateEmptyFields(DynamoHttpServletRequest pRequest)
	{
		validateFirstNameField (pRequest);
		validateLastNameField (pRequest);
		validateEmailField (pRequest);
		validateConfirmEmailField (pRequest);
		validatePasswordField (pRequest);
	}

	private void validateFirstNameField(DynamoHttpServletRequest pRequest) {
		StorePropertyManager storePropertyManager =  (StorePropertyManager) getProfileTools().getPropertyManager();
		if (StringUtils.isEmpty(getStringValueProperty(storePropertyManager.getFirstNamePropertyName()))){
			String msg = formatUserMessage(MISSINGFIRSTNAME, pRequest);
			String path = generatePropertyPath(storePropertyManager.getFirstNamePropertyName());
			addFormException(new DropletFormException(msg, path));

		}

	}

	private void validateLastNameField(DynamoHttpServletRequest pRequest) {
		StorePropertyManager storePropertyManager =  (StorePropertyManager) getProfileTools().getPropertyManager();
		if(StringUtils.isEmpty(getStringValueProperty(storePropertyManager.getLastNamePropertyName()))){
			String msg = formatUserMessage(MISSINGLASTNAME, pRequest);
			String path = generatePropertyPath(storePropertyManager.getLastNamePropertyName());
			addFormException(new DropletFormException(msg, path));
		}

	}

	private void validateEmailField(DynamoHttpServletRequest pRequest) {
		StorePropertyManager storePropertyManager =  (StorePropertyManager) getProfileTools().getPropertyManager();
		String email = getStringValueProperty(storePropertyManager.getEmailAddressPropertyName());
		if(StringUtils.isEmpty(email)){
			String msg = formatUserMessage(MISSINGEMAILNAME, pRequest);
			String path = generatePropertyPath(storePropertyManager.getEmailAddressPropertyName());
			addFormException(new DropletFormException(msg, path));
		}
		else
		{
			StoreProfileTools profileTools = (StoreProfileTools)getProfileTools();
			if(!profileTools.validateEmailAddress(email)){
				String msg = formatUserMessage(INVALIDEMAILFIELD, pRequest);
				String path = generatePropertyPath(storePropertyManager.getEmailAddressPropertyName());
				addFormException(new DropletFormException(msg, path));
			}

		}
	}

	private void validateConfirmEmailField(DynamoHttpServletRequest pRequest) {
		if (StringUtils.isEmpty(getStringValueProperty(CONFIRMEMAIL_PARAM))){
			String msg = formatUserMessage(MISSINGCONFIRMFIELD, pRequest);
			String path = generatePropertyPath(CONFIRMEMAIL_PARAM);
			addFormException(new DropletFormException(msg, path));
		}
	}


	private void validatePasswordField(DynamoHttpServletRequest pRequest) {
		StorePropertyManager storePropertyManager =  (StorePropertyManager) getProfileTools().getPropertyManager();
		if (StringUtils.isEmpty(getStringValueProperty(storePropertyManager.getPasswordPropertyName()))){
			String msg = formatUserMessage(MISSINGPASSWORD, pRequest);
			String path = generatePropertyPath(storePropertyManager.getPasswordPropertyName());
			addFormException(new DropletFormException(msg, path));
		}
	}

	@Override
	protected void preUpdateUser(DynamoHttpServletRequest arg0,
			DynamoHttpServletResponse arg1) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
		StorePropertyManager propertyManager = (StorePropertyManager)getProfileTools().getPropertyManager();

		if(null!= getValue().get(propertyManager.getEmailAddressPropertyName())){
			String email = (String) getValue().get(propertyManager.getEmailAddressPropertyName());
			if (!getStringValueProperty(propertyManager.getEmailAddressPropertyName()).equalsIgnoreCase(getStringValueProperty(CONFIRMEMAIL_PARAM))){
				String msg = formatUserMessage("confirmEmailDoNotMatch", arg0);
				String path = generatePropertyPath(CONFIRMEMAIL_PARAM);
				addFormException(new DropletFormException(msg, path));
			}
			else
			{
				String password = (String)getValue().get(propertyManager.getPasswordPropertyName());
				String login = (String)getProfile().getPropertyValue(propertyManager.getLoginPropertyName());
				boolean bIsAuthenticate;
				try {
					bIsAuthenticate = getIdentityManager().authenticateByPassword(login, password);
					if(!bIsAuthenticate)
					{
						String msg = formatUserMessage("pwdDoesntMatch", arg0);
						String path = generatePropertyPath(propertyManager.getPasswordPropertyName());
						addFormException(new DropletFormException(msg, path));
					}
				} catch (SecurityException e) {
					vlogError("Exception while updating user"+e.getMessage());
				}
			}
			setValueProperty(propertyManager.getLoginPropertyName(),email);
			getValue().remove(CONFIRMEMAIL_PARAM);
		}
		if(getValue().get(SECURITY_QUESTION_UPDATE) != null && Boolean.parseBoolean((String)getValue().get(SECURITY_QUESTION_UPDATE)))
		{
			String securityAns = (String)getValue().get(SECURITY_ANSWER);
			if(StringUtils.isEmpty(securityAns))
			{
				String msg = formatUserMessage(SECURITY_ANSWER_IS_EMPTY, arg0);
				String path = generatePropertyPath(SECURITY_ANSWER);
				addFormException(new DropletException(msg,path));
			}
			getValue().remove(SECURITY_QUESTION_UPDATE);
		}
		if(getValue().get(FIRST_NAME_UPDATED) != null && Boolean.parseBoolean((String)getValue().get(FIRST_NAME_UPDATED)))
		{
			String firstName = (String)getValue().get(propertyManager.getFirstNamePropertyName());
			if(StringUtils.isEmpty(firstName))
			{
				String msg = formatUserMessage(MISSINGFIRSTNAME, arg0);
				String path = generatePropertyPath(propertyManager.getFirstNamePropertyName());
				addFormException(new DropletException(msg,path));
			}
			getValue().remove(FIRST_NAME_UPDATED);
		}
		if(getValue().get(LAST_NAME_UPDATED) != null && Boolean.parseBoolean((String)getValue().get(LAST_NAME_UPDATED)))
		{
			String lastName = (String)getValue().get(propertyManager.getLastNamePropertyName());
			if(StringUtils.isEmpty(lastName))
			{
				String msg = formatUserMessage(MISSINGLASTNAME, arg0);
				String path = generatePropertyPath(propertyManager.getLastNamePropertyName());
				addFormException(new DropletException(msg,path));
			}
			getValue().remove(LAST_NAME_UPDATED);
		}
		if(getValue().get(PASSWORD_UPDATED) != null && Boolean.parseBoolean((String)getValue().get(PASSWORD_UPDATED)))
		{
			String password = (String)getValue().get(propertyManager.getPasswordPropertyName());
			if(StringUtils.isEmpty(password))
			{
				String msg = formatUserMessage(MISSINGPASSWORD, arg0);
				String path = generatePropertyPath(propertyManager.getPasswordPropertyName());
				addFormException(new DropletException(msg,path));
			}
			getValue().remove(PASSWORD_UPDATED);
		}
		if(getValue().get(PHONE_TYPE_UPDATE) != null && Boolean.parseBoolean((String)getValue().get(PHONE_TYPE_UPDATE)))
		{
			String phoneTypeUpdate = (String)getValue().get(PHONE_TYPE_UPDATE);
			if(StringUtils.isEmpty(phoneTypeUpdate))
			{
				String msg = formatUserMessage(PHONE_TYPE_EMPTY, arg0);
				String path = generatePropertyPath(PHONE_TYPE_UPDATE);
				addFormException(new DropletException(msg,path));
			}
			getValue().remove(PHONE_TYPE_UPDATE);
		}
	}

	/**
	 * Validate user entered address
	 *
	 * @param pReq
	 * @param pRes
	 */

	public void preAddAddress(DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes){
		String postalCode = profileContact.getPostalCode();
		if(!validationManager.validpostalCode(postalCode)){
			String msg = formatUserMessage(WRONGPOSTALCODE, pReq);
			String path = generatePropertyPath("postalCode");
			addFormException(new DropletException(msg,path));
		}
		String phoneNo = profileContact.getPhoneNumber();
		if(!validationManager.validpostalCode(phoneNo)){
			String msg = formatUserMessage(WRONGPHONENO, pReq);
			String path = generatePropertyPath("phoneNumber");
			addFormException(new DropletException(msg,path));
		}
	}


	/**
	 * Method called when the user delete his address in the address book
	 * @param pRequest
	 * @param pResponse
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public boolean handleDeleteAddressFromAddressBook(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse) throws ServletException, IOException {

		if (isLoggingDebug()) {
			logDebug("BEGIN:::Entering BNProfileFormHandler.handleDeleteAddressFromAddressBook Method. ::");
		}

		boolean isError = false;
		String myHandler = "BNProfileFormHandler.handleDeleteAddressFromAddressBook";
		RepeatingRequestMonitor rrm = getRepeatingRequestMonitor();
		if ((rrm == null) || (rrm.isUniqueRequestEntry(myHandler))) {
			TransactionDemarcation td = new TransactionDemarcation();
			try {
				td.begin(getTransactionManager(), 4);
				String nickName = getNickName();
				Profile profile = getProfile();
				getProfileManager().deleteAddressFromAddressBook(profile, nickName);
			} catch (RepositoryException e) {
				isError = true;

				logError("RepositoryException Caused at :: BNProfileFormHandler : handleDeleteAddressFromAddressBook() method .." + e.getMessage());
			} catch (TransactionDemarcationException e) {
				isError = true;

				logError("TransactionException Caused at :: BNProfileFormHandler : handleDeleteAddressFromAddressBook() method .." + e.getMessage());
			} finally {
				try {
					td.end(isError);
				} catch (TransactionDemarcationException e) {
					isError = true;
					logError("TransactionException Caused at :: BNProfileFormHandler : handleDeleteAddressFromAddressBook() method .." + e.getMessage());
				}
			}
			if (isLoggingDebug()) {
				logDebug("END:::BNProfileFormHandler.handleDeleteAddressFromAddressBook Method. ::");
			}
			return checkFormRedirect(getDeleteAddressFromAddressBookSuccessURL(), getDeleteAddressFromAddressBookErrorURL(), pRequest, pResponse);
		}

		return true;
	}


	public void deleteAddressFromAddressBook(Profile pProfile, String nickName) throws RepositoryException {

		if (isLoggingDebug()) {
			logDebug("Entering ProfileManager.deleteAddressFromAddressBook method.");
		}
		BNProfileTools bnProfileTools = (BNProfileTools)getProfileTools();
		bnProfileTools.deleteAddressFromAddressBook(pProfile,nickName);

	}

	public boolean handleAddAddress (DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes) throws ServletException, IOException{

		logDebug("Start::handleAddAddress");
		logDebug("handleAddProfileAddress - firstName  : " +profileContact.getFirstName());
		logDebug("handleAddProfileAddress - lastName : " +profileContact.getLastName());
		logDebug("handleAddProfileAddress - aprt : " +profileContact.getAddress1());
		logDebug("handleAddProfileAddress - city : " +profileContact.getCity());
		logDebug("handleAddProfileAddress - country : " +profileContact.getCountry());
		logDebug("handleAddProfileAddress - companyName: " +profileContact.getCompanyName());
		logDebug("handleAddProfileAddress - state : " +profileContact.getState());
		logDebug("handleAddProfileAddress - Zipcode : " +profileContact.getPostalCode());
		logDebug("handleAddProfileAddress - phoneNo : " +profileContact.getPhoneNumber());


		preAddAddress(pReq, pRes);
		if(getFormError())
			checkFormRedirect(getAddressSuccessURL(), getAddressErrorURL(), pReq, pRes);
		addAddress();
		postAddAddress(pReq, pRes);
		logDebug("End::handleAddProfileAddress");
		return checkFormRedirect(getAddressSuccessURL(), getAddressErrorURL(), pReq, pRes);
	}

	/**
	 * add user entered address to profile secondary address
	 *
	 */
	public void addAddress(){
		Profile profile = getProfile();
		StoreProfileTools profileTools = (StoreProfileTools)getProfileTools();
		Map newAddress = getEditValue();

		String nickName = (String) newAddress.get(getNicknameValueMapKey());
		if(StringUtils.isBlank(nickName)){
			nickName = profileTools.getUniqueShippingAddressNickname(profileContact, profile, null);
		}

		TransactionManager tm = getTransactionManager();
		TransactionDemarcation td = getTransactionDemarcation();
		try{
			if(tm != null){
				td.begin(tm, 3);
			}
			String newAddressId;
			try {
				newAddressId = profileTools.createProfileRepositorySecondaryAddress(profile, nickName, profileContact);
				setDefaultAddress (nickName,profileTools);
			} catch (RepositoryException e) {
				vlogError("BNProfileFormHandler: handleAddShippingAddress: RepositoryException", e);
			}
		}
		catch (TransactionDemarcationException e) {
			vlogError("BNProfileFormHandler: handleAddShippingAddress: TransactionDemarcationException", e);
			if (e.getMessage() != null) {
				addFormException(new DropletFormException(e.getMessage(), "", ""));
			}
		}
		finally {
			try {
				if (tm != null)
					td.end();
			} catch (TransactionDemarcationException e) {
				if (isLoggingError())
					logError("Can't end transaction ", e);
			}
		}
	}

	private void setDefaultAddress(String nickName,StoreProfileTools profileTools) {
		if(isUseShippingAddressAsDefault())
			try {
				profileTools.setDefaultShippingAddress(getProfile(), nickName);
			} catch (RepositoryException e) {
	            if (isLoggingError()) {
	                logError("Error while setting default shipping address", e);
	            }
	        }
	}

	public boolean handleUpdateDefaultShipAddress(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
            throws ServletException, IOException {
        StoreProfileTools storeProfileTools = (StoreProfileTools) getProfileTools();
        try {
        	String nickName =  getNickName();
            storeProfileTools.setDefaultShippingAddress(getProfile(), nickName);

        } catch (RepositoryException e) {
            if (isLoggingError()) {
                logError("Error while setting default shipping address", e);
            }
        }
        checkFormRedirect(getUpdateDefaultShipAddressSuccessURL(), getUpdateDefaultShipAddressErrorURL(), pRequest,
                pResponse);
        return true;
    }



	public boolean handleSetDefaultAddress (DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes) throws ServletException,IOException{
		String nickName = getNickName();
		StoreProfileTools profileTools = (StoreProfileTools)getProfileTools();
		try {
			profileTools.setDefaultShippingAddress(getProfile(), nickName);
		} catch (RepositoryException e) {
			if (isLoggingError()) {
                logError("Error while setting default shipping address", e);
            }
		}
		return checkFormRedirect(getAddressSuccessURL(), getAddressErrorURL(), pReq, pRes);
	}

	@Override
	public boolean handleCreateNewCreditCardAndAddress(
			DynamoHttpServletRequest Req, DynamoHttpServletResponse Resp)
			throws ServletException, IOException {
		preCreateNewCreditCardAndAddress(Req, Resp);
		boolean isNewAddress = false;
		HashMap newCard = (HashMap) getEditValue();
        HashMap newAddress = (HashMap) getBillAddrValue();
        StorePropertyManager propertyManager = getStorePropertyManager();
        BNCreditCardTools bnCreditCardTools = (BNCreditCardTools)getCreditCardTools();
        String ccType = bnCreditCardTools.getCreditCardType(newCard.get(propertyManager.getCreditCardNumberPropertyName()).toString());
        newCard.put(propertyManager.getCreditCardTypePropertyName(), ccType);
        String cardNickname = (String) newCard.get(propertyManager.getCreditCardNicknamePropertyName());
        StoreProfileTools profileTools = (StoreProfileTools) getProfileTools();
        Profile profile = getProfile();
        String secondaryAddrNickname = null;
        if (StringUtils.isEmpty(getNicknameValueMapKey())) {
            secondaryAddrNickname = (String) newAddress.get(getShippingAddressNicknameMapKey());
            isNewAddress = true;
        }
        try {
			cardNickname = profileTools.createProfileCreditCard(profile, newCard, cardNickname, newAddress,
			        secondaryAddrNickname, isNewAddress);
			newCard.clear();
            newAddress.clear();
		} catch (RepositoryException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		} catch (InstantiationException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		} catch (IllegalAccessException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		} catch (ClassNotFoundException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		} catch (IntrospectionException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		} catch (PropertyNotFoundException e) {
			if (isLoggingError()) {
                logError("Error while Creating new card", e);
			}
		}
        newCard.clear();
        newAddress.clear();
		return checkFormRedirect(getCreateCardSuccessURL(), getCreateCardErrorURL(), Req,
				Resp);
	}

	 protected boolean validateCreditCardEmptyFields(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse) {

	        StorePropertyManager propertyManager = getStorePropertyManager();
	        Map newCard = getEditValue();
	        BNCreditCardTools bnCreditCardTools = (BNCreditCardTools)getCreditCardTools();
	        String ccType = bnCreditCardTools.getCreditCardType(newCard.get(propertyManager.getCreditCardNumberPropertyName()).toString());
	        newCard.put(propertyManager.getCreditCardTypePropertyName(), ccType);
	        String[] cardProps = getCardProperties();
	        boolean missingFields = false;
	        Object property = null;
	        String propertyName = null;

	        for (int i = 0; i < cardProps.length; i++) {
	            propertyName = cardProps[i];
	            if (propertyName.equals(propertyManager.getCreditCardBillingAddressPropertyName()))
	                continue;
	            property = newCard.get(propertyName);
	            StringBuilder path = (new StringBuilder()).append(getAbsoluteName()).append(".editValue");
	            if (StringUtils.isBlank((String) property)) {
	            	String errorStr = formatUserMessage(APPEND_MISSING_ERROR_KEY, pRequest);
	            	errorStr += propertyName;
	                addFormException(new DropletException(errorStr,path.toString()));
	            }
	        }
	        // Verify that card number and expiry date are valid
	        ResourceBundle bundle = ResourceUtils.getBundle(RESOURCE_BUNDLE, getLocale(pRequest));
	        if (!validateCreditCard(newCard, bundle)) {
	          return false;
	        }
	        return true;
	    }


	 protected boolean validateBillingAddressFields(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse) {

		 HashMap newCard = (HashMap) getEditValue();
			HashMap newAddress = (HashMap) getBillAddrValue();
			Object property = null;
	        String propertyName = null;
			Iterator addressPropertyIterator = getRequiredBillingAddressPropertyList().iterator();
			StringBuilder path = (new StringBuilder()).append(getAbsoluteName()).append(".billAddrValue.");
			do {
	            if (!addressPropertyIterator.hasNext())
	                break;
	            propertyName = (String) addressPropertyIterator.next();
	            property = newAddress.get(propertyName);
	            if(StringUtils.isBlank((String) property)){
	            	String errorStr = formatUserMessage(APPEND_MISSING_ERROR_KEY, pRequest);
	            	errorStr += propertyName;
	                addFormException(new DropletException(errorStr,path.toString()));
	            }
	        } while (true);
			return true;
	    }

	@Override
	public boolean handleUpdateAddress(DynamoHttpServletRequest arg0,
			DynamoHttpServletResponse arg1) throws RepositoryException,
			ServletException, IOException {
		System.out.println("update Address------------");
		return super.handleUpdateAddress(arg0, arg1);
	}

	@Override
	protected void preCreateNewCreditCardAndAddress(
			DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {
		System.out.println("preCreateNewCreditCardAndAddress");
		validateCreditCardEmptyFields(pRequest,pResponse);
		validateBillingAddressFields(pRequest,pResponse);
		super.preCreateNewCreditCardAndAddress(pRequest, pResponse);
	}
	public void postAddAddress(DynamoHttpServletRequest pReq, DynamoHttpServletResponse pRes){

	}

	public boolean handleCreateMembership(DynamoHttpServletRequest arg0,
			DynamoHttpServletResponse arg1) throws RepositoryException,
			ServletException, IOException {
		String repositoryId = getProfile().getRepositoryId();
		RepositoryItem profileItem = getProfileTools().getProfileRepository().getItem(repositoryId, "user");
		if(profileItem !=null){
			MutableRepositoryItem mutableRepositoryItem = (MutableRepositoryItem) profileItem;
			mutableRepositoryItem.setPropertyValue("membershipId", MEMBERSHIP_ID);
			try {
				getProfileTools().getProfileRepository().updateItem(
						mutableRepositoryItem);
			} catch (RepositoryException e) {
				if (isLoggingError()) {
					logError("Error while updating Password : ", e);
				}
			}
		}

		return true;
	}

	/**
     * This method is used to update credit card
     *
     * @param pRequest
     * @param pResponse
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public boolean handleUpdateCreditCard(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
            throws ServletException, IOException {

        TransactionManager tm = getTransactionManager();
        TransactionDemarcation td = getTransactionDemarcation();
        StorePropertyManager propertyManager = getStorePropertyManager();
        StoreProfileTools profileTools = (StoreProfileTools) getProfileTools();
        Profile profile = getProfile();
        HashMap edit = (HashMap) getEditValue();
        HashMap billAddrValue = (HashMap) getBillAddrValue();

        String secondaryAddrNickname = null;
        if (StringUtils.isEmpty(getNicknameValueMapKey())) {
            secondaryAddrNickname = (String) billAddrValue.get(getShippingAddressNicknameMapKey());
        } else {
            secondaryAddrNickname = getNicknameValueMapKey();

            RepositoryItem addressItem = profileTools.getProfileAddress(getProfileItem(), secondaryAddrNickname);
            Map secondaryAddress = (Map) getProfile().getPropertyValue(
                    propertyManager.getSecondaryAddressPropertyName());
            secondaryAddress.get(secondaryAddrNickname);

            for (Object propertyName : getBillingAddressPropertyList()) {
                String name = propertyName.toString();
                if (null != addressItem && null != addressItem.getPropertyValue(name)) {
                    billAddrValue.put(name, addressItem.getPropertyValue(name));
                }
            }
        }
        RepositoryItem cardToUpdate = profileTools.getCreditCardById(creditCardID);

        edit.put(propertyManager.getCreditCardNumberPropertyName(),
                cardToUpdate.getPropertyValue(propertyManager.getCreditCardNumberPropertyName()));
        edit.put(propertyManager.getCreditCardTypePropertyName(),
                cardToUpdate.getPropertyValue(propertyManager.getCreditCardTypePropertyName()));
        edit.put(NAME_ON_CARD, cardToUpdate.getPropertyValue(NAME_ON_CARD));
        if (!(validateCreateCreditCardInformation(pRequest, pResponse, true))) {
            return checkFormRedirect(null, getUpdateCreditCardErrorURL(), pRequest, pResponse);
        }
        try {
            if (tm != null) {
                td.begin(tm, 3);
            }
            try {

                profileTools.updateProfileCreditCard(cardToUpdate, profile, edit, null, billAddrValue,
                        profileTools.getBillingAddressClassName());

                edit.clear();
                billAddrValue.clear();
            } catch (RepositoryException repositoryExc) {
                addFormException("errorCreatingCreditCard", repositoryExc, pRequest);

            } catch (InstantiationException ex) {
                throw new ServletException(ex);
            } catch (IllegalAccessException ex) {
                throw new ServletException(ex);
            } catch (ClassNotFoundException ex) {
                throw new ServletException(ex);
            } catch (IntrospectionException e) {
            	throw new ServletException(e);
			}
            return checkFormRedirect(getUpdateCreditCardSuccessURL(), getUpdateCreditCardErrorURL(), pRequest,
                    pResponse);
        } catch (TransactionDemarcationException e) {
            throw new ServletException(e);
        } finally {
            try {
                if (tm != null)
                    td.end();
            } catch (TransactionDemarcationException e) {
                if (isLoggingError())
                    logError("Can't end transaction ", e);
            }
        }
    }

    /**
     * This method used to populate Creditcard details
     *
     * @param pRequest
     * @param pResponse
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public boolean handlePopulateCreditCard(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
            throws ServletException, IOException {
        StorePropertyManager propertyManager = getStorePropertyManager();
        String id = getCreditCardID();
        BNProfileTools profileTools = (BNProfileTools) getProfileTools();
        RepositoryItem creditCardItem = profileTools.getCreditCardById(id);

        Map<String, Object> creditCardMap = getEditValue();
        creditCardMap.put(propertyManager.getCreditCardTypePropertyName(),
                creditCardItem.getPropertyValue(propertyManager.getCreditCardTypePropertyName()));
        creditCardMap.put(propertyManager.getCreditCardNumberPropertyName(),
                creditCardItem.getPropertyValue(propertyManager.getCreditCardNumberPropertyName()));
        creditCardMap.put(propertyManager.getCreditCardExpirationMonthPropertyName(),
                creditCardItem.getPropertyValue(propertyManager.getCreditCardExpirationMonthPropertyName()));
        creditCardMap.put(propertyManager.getCreditCardExpirationYearPropertyName(),
                creditCardItem.getPropertyValue(propertyManager.getCreditCardExpirationYearPropertyName()));
        creditCardMap.put(ProfileConstants.PROPERTY_NAME_ON_CREDIT_CARD,
                creditCardItem.getPropertyValue(ProfileConstants.PROPERTY_NAME_ON_CREDIT_CARD));

        return true;
    }

	public IdentityManager getIdentityManager() {
		return identityManager;
	}


	public void setIdentityManager(IdentityManager identityManager) {
		this.identityManager = identityManager;
	}


	public ContactInfo getProfileContact() {
		return profileContact;
	}


	public void setProfileContact(ContactInfo profileContact) {
		this.profileContact = profileContact;
	}


	public String getAddressSuccessURL() {
		return addressSuccessURL;
	}


	public void setAddressSuccessURL(String addressSuccessURL) {
		this.addressSuccessURL = addressSuccessURL;
	}


	public String getAddressErrorURL() {
		return addressErrorURL;
	}


	public void setAddressErrorURL(String addressErrorURL) {
		this.addressErrorURL = addressErrorURL;
	}

	public ValidationManager getValidationManager() {
		return validationManager;
	}

	public void setValidationManager(ValidationManager validationManager) {
		this.validationManager = validationManager;
	}

	public boolean isUseShippingAddressAsDefault() {
		return useShippingAddressAsDefault;
	}

		public void setUseShippingAddressAsDefault(boolean useShippingAddressAsDefault) {
		this.useShippingAddressAsDefault = useShippingAddressAsDefault;
	}

		public String getCreateCardSuccessURL() {
			return createCardSuccessURL;
		}

		public void setCreateCardSuccessURL(String createCardSuccessURL) {
			this.createCardSuccessURL = createCardSuccessURL;
		}

		public String getCreateCardErrorURL() {
			return createCardErrorURL;
		}

		public void setCreateCardErrorURL(String createCardErrorURL) {
			this.createCardErrorURL = createCardErrorURL;
		}

		public String getLoginSuccessURL() {
			return loginSuccessURL;
		}

		public void setLoginSuccessURL(String loginSuccessURL) {
			this.loginSuccessURL = loginSuccessURL;
		}

		public String getLoginErrorURL() {
			return loginErrorURL;
		}

		public void setLoginErrorURL(String loginErrorURL) {
			this.loginErrorURL = loginErrorURL;
		}

		public String getUpdatePhoneTypeSuccessURL() {
			return updatePhoneTypeSuccessURL;
		}

		public void setUpdatePhoneTypeSuccessURL(String updatePhoneTypeSuccessURL) {
			this.updatePhoneTypeSuccessURL = updatePhoneTypeSuccessURL;
		}

		public String getUpdatePhoneTypeErrorURL() {
			return updatePhoneTypeErrorURL;
		}

		public void setUpdatePhoneTypeErrorURL(String updatePhoneTypeErrorURL) {
			this.updatePhoneTypeErrorURL = updatePhoneTypeErrorURL;
		}

		public String getUpdateSecurityQuesSuccessURL() {
			return updateSecurityQuesSuccessURL;
		}

		public void setUpdateSecurityQuesSuccessURL(String updateSecurityQuesSuccessURL) {
			this.updateSecurityQuesSuccessURL = updateSecurityQuesSuccessURL;
		}

		public String getUpdateSecurityQuesErrorURL() {
			return updateSecurityQuesErrorURL;
		}

		public void setUpdateSecurityQuesErrorURL(String updateSecurityQuesErrorURL) {
			this.updateSecurityQuesErrorURL = updateSecurityQuesErrorURL;
		}

		public String getDeleteAddressFromAddressBookSuccessURL() {
			return deleteAddressFromAddressBookSuccessURL;
		}

		public void setDeleteAddressFromAddressBookSuccessURL(
				String deleteAddressFromAddressBookSuccessURL) {
			this.deleteAddressFromAddressBookSuccessURL = deleteAddressFromAddressBookSuccessURL;
		}

		public String getDeleteAddressFromAddressBookErrorURL() {
			return deleteAddressFromAddressBookErrorURL;
		}

		public void setDeleteAddressFromAddressBookErrorURL(
				String deleteAddressFromAddressBookErrorURL) {
			this.deleteAddressFromAddressBookErrorURL = deleteAddressFromAddressBookErrorURL;
		}

		public RepeatingRequestMonitor getRepeatingRequestMonitor() {

			return this.mRepeatingRequestMonitor;
		}

		public BNProfileManager getProfileManager() {
			return profileManager;
		}

		public void setProfileManager(BNProfileManager profileManager) {
			this.profileManager = profileManager;
		}

		public String getNickName() {
			return nickName;
		}

		public void setNickName(String nickName) {
			this.nickName = nickName;
		}

		public String getUpdateDefaultShipAddressSuccessURL() {
			return UpdateDefaultShipAddressSuccessURL;
		}

		public void setUpdateDefaultShipAddressSuccessURL(
				String updateDefaultShipAddressSuccessURL) {
			UpdateDefaultShipAddressSuccessURL = updateDefaultShipAddressSuccessURL;
		}

		public String getUpdateDefaultShipAddressErrorURL() {
			return UpdateDefaultShipAddressErrorURL;
		}

		public void setUpdateDefaultShipAddressErrorURL(
				String updateDefaultShipAddressErrorURL) {
			UpdateDefaultShipAddressErrorURL = updateDefaultShipAddressErrorURL;
		}


		public String getCreditCardID() {
			return creditCardID;
		}


		public void setCreditCardID(String creditCardID) {
			this.creditCardID = creditCardID;
		}


		public String getUpdateCreditCardErrorURL() {
			return UpdateCreditCardErrorURL;
		}


		public void setUpdateCreditCardErrorURL(String updateCreditCardErrorURL) {
			UpdateCreditCardErrorURL = updateCreditCardErrorURL;
		}


		public String getUpdateCreditCardSuccessURL() {
			return UpdateCreditCardSuccessURL;
		}


		public void setUpdateCreditCardSuccessURL(String updateCreditCardSuccessURL) {
			UpdateCreditCardSuccessURL = updateCreditCardSuccessURL;
		}


		public String getMembershipId() {
			return membershipId;
		}


		public void setMembershipId(String membershipId) {
			this.membershipId = membershipId;
		}


}

